//
//  ReBindView.m
//  Toyohu
//
//  Created by GuoPeng on 16/4/28.
//  Copyright © 2016年 celia. All rights reserved.
//

#import "ReBindView.h"
#import "FlatButton.h"
#import "UIView+Fillet.h"
#import "TieSuccessV.h"

#import <ReactiveCocoa.h>
#import "NSObject+PhoneNumber.h"

#import "GPAFNetworking3.h"
#import "LoginManager.h"
#import "TYH_LoginLoginModel.h"

#import "GPCustomMD.h"

typedef void (^SuccessBlock)(NSString *str);

@interface ReBindView ()
{
    
    NSInteger _time;
}


@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;
@property (weak, nonatomic) IBOutlet FlatButton *getVerificationCodeButton;
@property (weak, nonatomic) IBOutlet FlatButton *giveUpButton;
@property (weak, nonatomic) IBOutlet FlatButton *determineButton;

@property (nonatomic, copy) SuccessBlock successBlock;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (nonatomic, copy) NSString *oldValidCodeStr;

@property (nonatomic, strong) NSTimer *timer;


@end

@implementation ReBindView


- (void)viewHigher:(NSNotification*)note{
    //    CGRect frame = [[[[UIApplication sharedApplication] delegate] window] frame];
    //    if (frame.size.height == 480 && !_viewIsHigher) {
    //        [UIView animateWithDuration:0.4 animations:^{
    //            CGRect viewFrame = [self frame];
    //            viewFrame.origin.y = viewFrame.origin.y - 91;
    //            [self setFrame:viewFrame];
    //        } completion:^(BOOL finshed){
    //            _viewIsHigher = YES;
    //        }];
    //    }
    
    //    [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
    //        make.bottom.equalTo(self).offset(1);
    //    }];
    
    [UIView animateWithDuration:0.4f animations:^{
        self.bgView.center = CGPointMake(self.center.x, self.center.y - 100);
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)viewLower:(NSNotification*)note
{
    
//    self.bgView.center= CGPointMake(self.bgView.center.x, self.bgView.center.y + 100);
    [UIView animateWithDuration:1.0f animations:^{
        self.bgView.center = self.center;
        
    } completion:^(BOOL finished) {
        
    }];

    //    [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
    //        make.center.equalTo(self);
    //    }];
}

- (void)setKeyboard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewHigher:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewLower:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)bindEvents
{
    [self setKeyboard];
    
    @weakify(self);
    RAC(self.getVerificationCodeButton,enabled) = [RACSignal combineLatest:@[self.phoneTextField.rac_textSignal] reduce:^(NSString *phoneText){
        if ([phoneText isPhoneNumber]) {
            return @YES;
        }else{
            return @NO;
        }
    }];
    
    RAC(self.determineButton,enabled) = [RACSignal combineLatest:@[self.phoneTextField.rac_textSignal,self.verificationCodeTextField.rac_textSignal] reduce:^(NSString *phoneText,NSString *verificationCodeTex){
        return @([phoneText isPhoneNumber] && verificationCodeTex.length > 3);
    }];
    
    
    [[self.getVerificationCodeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        
        SHOW_STATUS
        
        [GPAFNetworking3 post:GETCODE parameters:@{@"phoneNum":self.phoneTextField.text} progress:nil success:^(id  _Nullable responseObject) {
            TYH_LoginLoginModel *model = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
            if (model.code != 1) {
                SHOW_ERROR
            }else{
                SHOW_HIDDEN
            }
        } failure:^(NSString * _Nonnull errorLD) {
            SHOW_NTERROR
        }];

        
        
        _time = 5;
        self.getVerificationCodeButton.enabled = NO;
        self.timer.fireDate = [NSDate distantPast];
        //        self.phoneNumberTextfield.enabled = NO;

//        [GPAFNetworking3 post:GetVerifyCode parameters:@{@"client":DEMAND,@"module":@"userRegister",@"mobile":self.phoneNumberTextfield.text} progress:^(NSProgress * _Nullable progress) {
//            
//        } success:^(id  _Nullable responseObject) {
//            YCDemandRegister *demandModel = [[YCDemandRegister alloc] initWithDictionary:responseObject];
//            if (![demandModel.resultCode isEqualToString:@"0"]) {
//                [SVProgressHUD showErrorWithStatus:demandModel.resultInfo];
//            }
//            
//            
//        } failure:^(NSString * _Nonnull errorLD) {
//            [SVProgressHUD showErrorWithStatus:errorLD];
//        }];
        
    }];
    
    self.timer = [self getTimer];
//    self.timeLabel.hidden = YES;
    
}

- (NSTimer *)getTimer{
    NSTimeInterval timeInterval = 1.0 ;
    NSTimer *atimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(decreaseTime) userInfo:nil repeats:YES];
    atimer.fireDate = [NSDate distantFuture];
    return atimer;
}

- (void)decreaseTime
{
    
    NSLog(@"%zi",_time);
    _time --;
    
    [self.getVerificationCodeButton setTitle:[NSString stringWithFormat:@"%ld",_time] forState:UIControlStateNormal];
    
//    self.obtainButton.hidden = YES;
//    self.timeLabel.text = [NSString stringWithFormat:@"%ziS",_time];
//    self.timeLabel.hidden = NO;
    
    if (!_time) {
        self.timer.fireDate = [NSDate distantFuture];
        self.getVerificationCodeButton.enabled = YES;
        [self.getVerificationCodeButton setTitle:[NSString stringWithFormat:@"重新获取" ] forState:UIControlStateNormal];
//        self.obtainButton.hidden = NO;
//        self.timeLabel.hidden = YES;
    }
}


- (void)initView{
    self.giveUpButton.clipsToBounds = YES;
    self.giveUpButton.layer.cornerRadius = self.giveUpButton.frame.size.height / 2;
    self.giveUpButton.layer.borderColor = [UIColor orangeColor].CGColor;
    self.giveUpButton.layer.borderWidth = 1.0f;
    
    self.determineButton.clipsToBounds = YES;
    self.determineButton.layer.cornerRadius = self.determineButton.frame.size.height / 2;
    self.determineButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.determineButton.layer.borderWidth = 1.0f;
    
    [self.bgView filletWithcornerRadius:8.0f];
    
    self.getVerificationCodeButton.clipsToBounds = YES;
    self.getVerificationCodeButton.layer.cornerRadius = self.getVerificationCodeButton.frame.size.height / 2;
    self.getVerificationCodeButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.getVerificationCodeButton.layer.borderWidth = 1.0f;
    
}
- (IBAction)getVerificationCodeClick:(id)sender
{
    
}
- (IBAction)giveUpClick:(id)sender
{
    [self removeFromSuperview];
}
- (IBAction)determineClick:(id)sender {
    self.successBlock(@"asdf");
    [self removeFromSuperview];
    
    WS
    [GPAFNetworking3 post:ChangePhoneNum parameters:@{@"pId":[[LoginManager shareLoginManager] getPid],@"newValidCode":self.verificationCodeTextField.text,@"oldValidCode":self.oldValidCodeStr,@"newPhoneNum":self.phoneTextField.text} progress:nil success:^(id  _Nullable responseObject) {
        SS
        TYH_LoginLoginModel *model = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (model.code != 1) {
            SHOW_ERROR
        }else{
            SHOW_HIDDEN
            [strongSelf removeFromSuperview];
            strongSelf.successBlock(strongSelf.verificationCodeTextField.text);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changePhone" object:strongSelf.phoneTextField.text];
        }
    } failure:^(NSString * _Nonnull errorLD) {
        SHOW_NTERROR
    }];
    
}

+ (void)show:(NSString *)vCode
{
    [[[self alloc] init] initWithSuccessBlock:^(NSString *str) {
        
        [TieSuccessV show];
        
    } frame:[[UIScreen mainScreen] bounds] vCode:vCode];
}

- (instancetype)initWithSuccessBlock:(void (^)(NSString *str))successBlock frame:(CGRect)frame vCode:(NSString *)vCode
{
    self = [[[NSBundle mainBundle] loadNibNamed:@"ReBindView" owner:self options:nil] objectAtIndex:0];
    if (self) {
        self.frame = frame;
        
        [self initView];
        [self bindEvents];
        _successBlock = successBlock;
        self.oldValidCodeStr = vCode;
        [[[UIApplication sharedApplication] keyWindow] addSubview:self];
        
    }
    return self;
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
